import fs from 'fs';
import md5 from 'md5';
import Identicon from 'identicon.js';
import { Random } from 'meteor/random';
import { cosConf, cos } from '../files/cos';

Accounts.onCreateUser((options, user) => {
  const username = options.username;
  const hash = md5(username);
  const styles = {
    margin: 0.2,
    size: 200
  };

  const base64String = new Identicon(hash, styles).toString();
  const fileName = `${Random.id()}-hash-avatar.png`;
  const localFilePath = `./assets/app/${fileName}`;
  const filePath = `users/${user._id}/profile/${fileName}`;

  fs.writeFileSync(localFilePath, base64String, {encoding: 'base64'});

  cos.putObject({
    Bucket: cosConf.Bucket,
    Region: cosConf.Region,
    Key: filePath,
    Body: fs.createReadStream(localFilePath),
    ContentLength: fs.statSync(localFilePath).size
  }, () => {
    fs.unlinkSync(localFilePath);
  });

  user.profile = {
    avatar: `https://${cosConf.Bucket}.cos.${cosConf.Region}.myqcloud.com/${filePath}`
  };
  
  return user;
});